﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace awaitform
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Does();
        }
        async void settext()
        {
            Console.WriteLine("settext start" + Thread.CurrentThread.ManagedThreadId);
            await Task.Run(() =>
            {
                Thread.Sleep(2000);
                Console.WriteLine("await" + Thread.CurrentThread.ManagedThreadId);
                
            });
            Console.WriteLine("settext end" + Thread.CurrentThread.ManagedThreadId);
            textBox1.Text = "test111";
        }

        private Task<string> DoWork()
        {
            return Task.Run(() =>
            {
                Console.WriteLine("DoWorking:" + Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(4000);
                return "Done with work!";
            }
                );
        }
        private async void Does()
        {
            Console.WriteLine("settext start" + Thread.CurrentThread.ManagedThreadId); //主线程 调用 button_Click 的线程
            string text = await DoWork();
            Console.WriteLine("After DoWork:" + Thread.CurrentThread.ManagedThreadId); //从辅助线程返回的 调用线程，此处为主线程
            textBox1.Text = text;
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            Console.WriteLine("settext start" + Thread.CurrentThread.ManagedThreadId); //主线程 调用 button_Click 的线程
            string text = await DoWork();
            Console.WriteLine("After DoWork:" + Thread.CurrentThread.ManagedThreadId); //从辅助线程返回的 调用线程，此处为主线程
            textBox1.Text = text;
        }

        private async void button2_Click(object sender, EventArgs e)
        {
            Console.WriteLine("settext start" + Thread.CurrentThread.ManagedThreadId); //主线程 调用 button_Click 的线程
            string text1 = await DoWork();
            Console.WriteLine("After DoWork1:" + Thread.CurrentThread.ManagedThreadId);
            string text2 = await DoWork();
            Console.WriteLine("After DoWork2:" + Thread.CurrentThread.ManagedThreadId);
            textBox1.Text = text1+text2;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            
        }

        private async Task RunAsync()
        {
            await Task.Run(()=> Thread.Sleep(1000));
        }
    }
}
